import { get, post, put, del } from "./api";

export const userService = {
  async getUsers(params = { page: 1, pageSize: 10 }) {
    try {
      // 获取所有用户数据
      const response = await get("users");
      const allUsers = Array.isArray(response)
        ? response
        : response.content || [];

      // 在前端处理分页
      const startIndex = (params.page - 1) * params.pageSize;
      const endIndex = startIndex + params.pageSize;
      const paginatedUsers = allUsers.slice(startIndex, endIndex);

      return {
        items: paginatedUsers,
        total: allUsers.length,
        totalPages: Math.ceil(allUsers.length / params.pageSize),
        currentPage: params.page,
      };
    } catch (error) {
      throw new Error(error.message || "获取用户列表失败");
    }
  },

  async getAllUsers() {
    try {
      const response = await get("users");
      return Array.isArray(response) ? response : response.content || [];
    } catch (error) {
      throw new Error(error.message || "获取用户列表失败");
    }
  },

  async getUser(id) {
    try {
      const userId = parseInt(id);
      if (isNaN(userId)) {
        throw new Error("无效的用户ID");
      }
      const response = await get(`users/${userId}`);
      return response;
    } catch (error) {
      if (error.response?.status === 404) {
        throw new Error("用户不存在");
      }
      throw new Error(error.message || "获取用户信息失败");
    }
  },

  async createUser(userData) {
    try {
      const response = await post("users", userData, true);
      return response;
    } catch (error) {
      throw new Error(error.message || "创建用户失败");
    }
  },

  async updateUser(id, userData) {
    try {
      const userId = parseInt(id);
      if (isNaN(userId)) {
        throw new Error("无效的用户ID");
      }
      const response = await put(`users/${userId}`, userData, true);
      return response;
    } catch (error) {
      throw new Error(error.message || "更新用户失败");
    }
  },

  async deleteUser(id) {
    try {
      const userId = parseInt(id);
      if (isNaN(userId)) {
        throw new Error("无效的用户ID");
      }
      const response = await del(`users/${userId}`);
      return response;
    } catch (error) {
      throw new Error(error.message || "删除用户失败");
    }
  },

  getCurrentUser: async () => {
    try {
      const response = await get("current-user");
      return (
        response || {
          username: "张三",
          avatar: "assets/img/users/user-3.png",
        }
      );
    } catch (error) {
      console.error("获取当前用户信息失败:", error);
      return {
        username: "张三",
        avatar: "assets/img/users/user-3.png",
      };
    }
  },

  async batchDeleteUsers(userIds) {
    try {
      // 使用 Promise.all 并行执行所有删除操作
      const deletePromises = userIds.map((id) => this.deleteUser(id));
      await Promise.all(deletePromises);
      return { success: true };
    } catch (error) {
      console.error("批量删除用户失败:", error);
      throw error;
    }
  },
};
